<template>
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="关键字">
            <el-input
              v-model="queryDto.name"
              style="width: 100%"
              placeholder="帖子名字"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类">
            <el-cascader
              :props="categoryProps"
              style="width: 100%"
              v-model="searchCategoryIdList"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display: flex">
        <el-button type="primary" size="small" @click="fetchData">
          搜索
        </el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <el-table :data="list" style="width: 100%">
    <el-table-column
      prop="sliderUrls"
      label="轮播图"
      #default="scope"
      width="200"
    >
      <div style="height: 50px; float: left">
        <img
          v-for="(item, index) in scope.row.sliderUrls"
          :key="index"
          :src="item"
          width="50"
        />
      </div>
    </el-table-column>
    <el-table-column prop="name" label="帖子标题" width="160" />
    <el-table-column prop="userName" label="发帖人名称" />
    <el-table-column prop="content" label="贴子内容" />
    <el-table-column prop="category1Name" label="一级分类" />
    <el-table-column prop="category2Name" label="二级分类" />
    <el-table-column prop="auditStatus" label="审核状态" #default="scope">
      {{
        scope.row.auditStatus == 0
          ? '未审核'
          : scope.row.auditStatus == 1
          ? '通过'
          : '驳回'
      }}
    </el-table-column>
    <el-table-column label="操作" align="center" width="200" #default="scope">
      <el-button
        type="primary"
        size="small"
        @click="editShow(scope.row)"
        style="padding: 5px; margin-left: 5px"
      >
        修改
      </el-button>
      <el-button
        type="danger"
        size="small"
        @click="remove(scope.row.id)"
        style="padding: 5px; margin-left: 5px"
      >
        删除
      </el-button>
      <el-button
        v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == -1"
        type="scope.row.auditStatus === -1 ? 'warning' : 'success'"
        size="small"
        @click="audit(scope.row.id)"
        style="padding: 5px; margin-left: 5px"
      >
        {{ scope.row.auditStatus === -1 ? '审核不通过' : '审批' }}
      </el-button>
    </el-table-column>
  </el-table>

  <!-- 修改帖子 -->
  <el-dialog v-model="dialogPostVisible" title="修改帖子" width="80%">
    <el-form
      label-width="120px"
      style="margin-top: 20px; padding: 20px; background-color: #f9fafc; border-radius: 8px;"
      :label-position="labelPosition"
    >
      <el-form-item label="帖子标题">
        <el-input v-model="post.name" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="帖子内容">
        <el-input
          v-model="post.content"
          type="textarea"
          :rows="4"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="分类">
        <el-cascader
          style="width: 100%;"
          :props="categoryProps"
          v-model="categoryIdList"
          @change="categoryChange"
        />
      </el-form-item>
      <el-form-item label="发帖人名称">
        <el-input v-model="post.userName" style="width: 100%;" disabled />
      </el-form-item>
      <el-form-item label="审核状态">
        <el-input v-model="auditStatusText" style="width: 100%;" disabled />
      </el-form-item>
      <el-form-item label="帖子图片">
        <el-upload
          v-model:file-list="fileList"
          action="http://localhost:8505/admin/system/fileUpload"
          list-type="picture-card"
          multiple
          :on-success="handleSliderSuccess"
          :on-remove="handleRemove"
          :headers="postheaders"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item style="text-align: right;">
        <el-button
          type="primary"
          @click="saveOrUpdate"
          style="margin-right: 10px;"
        >
          提交
        </el-button>
        <el-button @click="dialogPostVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 审核 -->

  <el-dialog v-model="dialogAuditVisible" title="审核" width="80%">
    <el-form
      :model="product"
      label-width="120px"
      style="margin-top: 20px; padding: 20px; background-color: #f9fafc; border-radius: 8px;"
    >
      <el-divider />
      <span style="margin-bottom: 5px; font-weight: bold;">帖子详情</span>
      <el-row>
        <el-col :span="12">
          <el-form-item label="帖子标题">
            {{ post.name }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类">
            {{ post.category1Name }} => {{ post.category2Name }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="帖子内容">
            {{ post.content }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="创建时间">
            {{ post.createTime }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            {{
              post.auditStatus == 0
                ? '未审核'
                : post.auditStatus == 1
                ? '通过'
                : '驳回'
            }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="轮播图">
            <el-image
              v-for="(item, index) in sliderUrlList"
              :key="index"
              :src="item"
              style="width: 100px; height: 100px; margin-right: 10px; border-radius: 5px"
              fit="cover"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item style="text-align: right;">
        <el-button
          type="success"
          size="large"
          @click="updateAuditStatus(post.id, 1)"
          style="margin-right: 10px;"
        >
          通过
        </el-button>
        <el-button
          type="warning"
          size="large"
          plain
          @click="updateAuditStatus(post.id, -1)"
          style="margin-right: 10px;"
        >
          驳回
        </el-button>
        <el-button size="large" @click="dialogAuditVisible = false">
          取消
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    @size-change="fetchData()"
    @current-change="fetchData()"
  />
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
//import { FindAllBrand } from '@/api/brand.js'
import { FindCategoryByParentId } from '@/api/category.js'
import {
  GetPostPageList,
  UpdatePostById,
  GetPostById,
  DeletePostById,
  UpdatePostAuditStatus,
} from '@/api/postManager.js'
import { useApp } from '@/pinia/modules/app'
import { ElMessage, ElMessageBox } from 'element-plus'

////////////////////////////////////////审核
const dialogAuditVisible = ref(false)

const audit = async id => {
  const { data } = await GetPostById(id)
  post.value = data

  //分类赋值
  categoryIdList.value = [post.value.category1Id, post.value.category2Id]

  //处理图片
  fileList.value = []
  if (post.value.sliderUrls) {
    sliderUrlList.value = post.value.sliderUrls.split(',')
  }
  sliderUrlList.value.forEach(url => {
    fileList.value.push({ url: url })
  })
  dialogAuditVisible.value = true
}

const updateAuditStatus = async (id, auditStatus) => {
  await UpdatePostAuditStatus(id, auditStatus)
  dialogAuditVisible.value = false
  ElMessage.success('操作成功')
  fetchData()
}

///////////////////////////////////////修改帖子信息

const dialogPostVisible = ref(false)

// 分类级联选择器选中数据以后的数据模型
const categoryIdList = ref([])

// 分类级联选择器数据发送改变以后的事件处理函数
const categoryChange = async () => {
  if (categoryIdList.value.length == 2) {
    post.value.category1Id = categoryIdList.value[0]
    post.value.category2Id = categoryIdList.value[1]
  }
}

const saveOrUpdate = () => {
  console.log('submit!' + post.value)
  post.value.sliderUrls = sliderUrlList.value.join(',')
  updateData()
}

// 修改
const updateData = async () => {
  console.log(post.value)
  await UpdatePostById(post.value)
  dialogPostVisible.value = false
  ElMessage.success('修改成功')
  fetchData()
}

// 上传帖子图片
const sliderUrlList = ref([])
const postheaders = {
  token: useApp().authorization.token, // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}
const handleRemove = (uploadFile, uploadFiles) => {
  sliderUrlList.value.splice(sliderUrlList.value.indexOf(uploadFile.url), 1)
}
const fileList = ref([])
const handleSliderSuccess = (response, uploadFile) => {
  sliderUrlList.value.push(response.data)
}

// 进入修改
const editShow = row => {
  getById(row.id)
  dialogPostVisible.value = true
}

// 获取帖子详情
const getById = async id => {
  const { data } = await GetPostById(id)
  post.value = data

  // 分类赋值
  categoryIdList.value = [post.value.category1Id, post.value.category2Id]

  // 处理图片
  fileList.value = []
  sliderUrlList.value = post.value.sliderUrls.split(',')
  sliderUrlList.value.forEach(url => {
    fileList.value.push({ url: url })
  })
}

//////////////////////////////分页列表查询 start

const list = ref([])

const total = ref(0)

//分类列表
const categoryProps = ref({
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  async lazyLoad(node, resolve) {
    // 加载数据的方法
    if (typeof node.value == 'undefined') node.value = 0
    const { data } = await FindCategoryByParentId(node.value)
    data.forEach(function(item) {
      // hasChildren判断是否有子节点
      item.leaf = !item.hasChildren
    })
    resolve(data) // 返回数据
  },
})

// 选中的数据模型
const queryDto = ref({ category1Id: '', category2Id: '', name: '' })
const searchCategoryIdList = ref([])

//分页
const pageParamsForm = {
  page: 1,
  limit: 3,
}

const pageParams = ref(pageParamsForm)

//钩子函数
onMounted(() => {
  fetchData()
})
// 表单数据模型
const post = ref({
  id: '',
  name: '',
  userName: '',
  category1Id: '',
  category2Id: '',
  sliderUrls: '',
  content: '',
  auditStatus: 0,
})

// 添加计算属性来格式化审核状态文本
const auditStatusText = computed(() => {
  return post.value.auditStatus === 0
    ? '未审核'
    : post.value.auditStatus === 1
    ? '通过'
    : '驳回'
})

// 分页列表查询方法
const fetchData = async () => {
  // 请求后端接口
  if (searchCategoryIdList.value.length === 2) {
    queryDto.value.category1Id = searchCategoryIdList.value[0]
    queryDto.value.category2Id = searchCategoryIdList.value[1]
  } else {
    queryDto.value.category1Id = ''
    queryDto.value.category2Id = ''
  }
  const { data } = await GetPostPageList(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  console.log('postManager', data)
  data.list.forEach(item => {
    if (item.sliderUrls) {
      item.sliderUrls = item.sliderUrls.split(',')
    }
  })

  // 将响应结果数据设置给对应的属性模型
  list.value = data.list
  total.value = data.total
}

/////////////////////////////////////删除
const remove = async id => {
  console.log('removeDataById:' + id)
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await DeletePostById(id)
      ElMessage.success('删除成功')
      fetchData()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

const resetData = () => {
  queryDto.value = { category1Id: '', category2Id: '', name: '' }
  searchCategoryIdList.value = []
  fetchData()
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tag-group__title {
  margin-right: 10px; /* 调整元素之间的水平间距 */
}

.specValue {
  margin-bottom: 10px;
  margin-top: 10px;
  font-size: 14px;
}

.avatar-uploader .avatar {
  width: 50px;
  height: 50px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}
</style>
